import Router from 'koa-router'
import Redis from 'koa-redis'
import nodeMailer from 'nodemailer'
import Email from '../dbs/config'
import User from '../dbs/models/users'
import Passport from './utils/passport'
import axios from './utils/axios'

const router = new Router({ prefix: '/users' })

const Store = new Redis().client

router.post('/signup', async (ctx) => {
    const { username, password, email, code } = ctx.request.body

    if (code) {
        const saveCode = await Store.hget(`nodemail:${username}`, 'code')
        const saveExpire = await Store.hget(`nodemail:${username}`, 'expire')
        // 你自己输入的验证码与客户端比较保存下来的验证码作比较
        if (code === saveCode) {
            if (new Date().getTime() - saveExpire > 0) {
                ctx.body = {
                    code: -1,
                    msg: '验证码已过期，请重新尝试'
                }
                return false
            }
        } else {
            ctx.body = {
                code: -1,
                msg: '请填写正确的验证码'
            }
        }
    } else {
        ctx.body = {
            code: -1,
            msg: '请填写验证码'
        }
    }
    const user = await User.find({ username })
    if (user.length) {
        ctx.body = {
            code: -1,
            msg: '已被注册'
        }
        return
    }
    // 创建一个写入数据库的操作
    const nuser = await User.create({ username, password, email })
    if (nuser) {
        // 如果写入数据库成功了就进入一个自动登陆的过程
        const res = await axios.post('/users/signin', { username, password })
        if (res.data && res.data.code === 0) {
            ctx.body = {
                code: 0,
                msg: '注册成功',
                user: res.data.user
            }
        } else {
            ctx.body = {
                code: -1,
                msg: 'error'
            }
        }
    } else {
        ctx.body = {
            code: -1,
            msg: '注册失败'
        }
    }
})
// 登陆接口
router.post('/signin', async (ctx, next) => {
    // 调用一个passport-local策略 ,会返回四个信息
    return Passport.authenticate('local', function (err, user, info, status) {
        if (err) {
            ctx.body = {
                code: -1,
                msg: err
            }
        } else if (user) {
            ctx.body = {
                code: 0,
                msg: '登录成功',
                user
            }
            return ctx.login(user)
        } else {
            ctx.body = {
                code: 1,
                msg: info
            }
        }
    })(ctx, next)
})

// 请求验证码
router.post('/verify', async (ctx, next) => {
    const username = ctx.request.body.username
    // 在redis缓存中读取验证码过期时间
    const saveExpire = await Store.hget(`nodemail:${username}`, 'expire')
    // 验证码的还没过期的时候
    if (saveExpire && new Date().getTime() - saveExpire < 0) {
        ctx.body = {
            code: -1,
            msg: '验证请求过于频繁，1分钟内1次'
        }
        return false
    }
    // 发邮件对象
    const transporter = nodeMailer.createTransport({
        service: 'qq',
        // 验证邮箱用户和密码
        auth: {
            user: Email.smtp.user,
            pass: Email.smtp.pass
        }
    })
    // 发送的信息
    const ko = {
        code: Email.smtp.code(),
        expire: Email.smtp.expire(),
        email: ctx.request.body.email,
        user: ctx.request.body.username
    }
    // 邮件中显示内容的定义
    const mailOptions = {
        from: `"认证邮件" <${Email.smtp.user}>`,
        to: ko.email,
        subject: '《美团网全栈实战》注册码',
        html: `您在《美团网全栈实战》课程中注册，您的邀请码是${ko.code}`
    }
    // 执行发送邮箱功能
    await transporter.sendMail(mailOptions, (error, info) => {
        if (error) {
            return global.console.log(error)
        } else {
            // 发送成功后将内容在redis中存储存储
            Store.hmset(`nodemail:${ko.user}`, 'code', ko.code, 'expire', ko.expire, 'email', ko.email)
        }
    })
    ctx.body = {
        code: 0,
        msg: '验证码已发送，可能会有延时，有效期1分钟'
    }
})

router.get('/exit', async (ctx, next) => {
    // 注销用户
    await ctx.logout()
    // 检查是否登陆状态
    if (!ctx.isAuthenticated()) {
        ctx.body = {
            code: 0
        }
    } else {
        ctx.body = {
            code: -1
        }
    }
})

// 获取用户名
router.get('/getUser', async (ctx) => {
    if (ctx.isAuthenticated()) {
        // 在session中把用户名取出来
        const { username, email } = ctx.session.passport.user
        ctx.body = {
            user: username,
            email
        }
    } else {
        ctx.body = {
            user: '',
            email: ''
        }
    }
})

export default router
